package net.openl10n.packaging;

import net.openl10n.opc4j.PackagePart;

public abstract class OpenLocPartFactory<T extends OpenLocPart> {
	
	public abstract String getContentType();
	
	public abstract T create(OpenLocPartContainer container, PackagePart part, OpenLocPartFactoryManager partFactoryManager);

	public abstract String getRelationshipType();
	
	public abstract Class<T> getTargetClass();

	protected abstract String getPartNamePattern();

	// e.g. /document#.xml -> /document.xml
	//      /#/document.xml -> /document.xml
	public String getPartName(){
		String pattern = getPartNamePattern();
		int wildCardIndex = pattern.indexOf('#');
		if(wildCardIndex == -1)
			return pattern;
		boolean pathBefore = wildCardIndex == 0 ? false : pattern.charAt(wildCardIndex-1) == '/';
		boolean pathAfter = wildCardIndex == pattern.length()-1 ? false : pattern.charAt(wildCardIndex+1) == '/';
		if(pathBefore && pathAfter)
			pattern = pattern.substring(0,wildCardIndex) + pattern.substring(wildCardIndex+2, pattern.length()); 
		else
			pattern = pattern.substring(0,wildCardIndex) + pattern.substring(wildCardIndex+1, pattern.length());
		
		return pattern;
	}
	
	// /document#.xml -> /document1.xml
	public String getPartName(int num){
		String pattern = getPartNamePattern();
		int wildCardIndex = pattern.indexOf('#');
		if(wildCardIndex == -1){
			wildCardIndex = pattern.lastIndexOf('.');
			return pattern.substring(0,wildCardIndex) + num + pattern.substring(wildCardIndex, pattern.length());
		}
		return pattern.substring(0,wildCardIndex) + num + pattern.substring(wildCardIndex+1, pattern.length());
	}
	
	// document#.xml -> /documents/#/document.xml
	// or /documents/document#.xml
	public String getPartName(String prefix, int num){
		return prefix + getPartName(num);
	}
	
	// document.xml -> /prefix/document.xml
	public String getPartName(String prefix){
		return prefix + getPartName(); 
	}
	
	public boolean hasNameVariable(){
		return getPartNamePattern().indexOf('#') != -1;
	}
	
	public boolean isPathNameVariable(){
		String pattern = getPartNamePattern(); 
		int index = pattern.indexOf('#');
		if(index < 1) return false;
		if(index == pattern.length()-1) return false;
		return pattern.charAt(index-1) == '/' && pattern.charAt(index+1) == '/';
	}
	
/*
[Content_Types].
/_rels/.rels
/_rels/project.xml.rels
/project.xml
/documents/1/document.xml
/documents/1/_rels/document.xml.rels


[Content_Types].
/_rels/.rels
/_rels/document.xml.rels
/document.xml


*/
}
